//
//  XPhotoVideoView.m
//  XPhotoLibraryKit
//
//  Created by Wu,Xinting on 2018/3/21.
//

#import "XPhotoVideoView.h"
#import "XPhoto.h"
#import "UIImage+Resource.h"

@import MediaPlayer;
@interface XPhotoVideoView ()

@property (nonatomic, strong) MPMoviePlayerController *mpController;
@property (nonatomic, strong) UIButton *playButton;

@end

@implementation XPhotoVideoView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.playButton.center = self.center;
        [self.playButton addTarget:self action:@selector(clickPlay:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.playButton];
    }
    return self;
}

- (void)load {
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    [[PHImageManager defaultManager] requestAVAssetForVideo:self.photo.asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.mpController.contentURL = ((AVURLAsset *)asset).URL;
        });
    }];
}

- (void)play {
    if (![self.mpController.view.superview isEqual:self]) {
        [self insertSubview:self.mpController.view belowSubview:self.playButton];
    }
    [self.mpController play];
}

- (void)pause {
    [self.mpController pause];
}

- (void)clean {
    [self pause];
    [self.mpController.view removeFromSuperview];
    self.mpController.contentURL = nil;
    self.playButton.hidden = NO;
    [self bringSubviewToFront:self.playButton];
}

#pragma mark - Action
- (void)clickPlay:(UIButton *)btn {
    [self play];
    btn.hidden = YES;
}

#pragma mark - Get&Set
- (MPMoviePlayerController *)mpController {
    if (!_mpController) {
        _mpController = [[MPMoviePlayerController alloc] initWithContentURL:nil];
        _mpController.view.frame = self.bounds;
    }
    return _mpController;
}

- (UIButton *)playButton {
    if (!_playButton) {
        _playButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        [_playButton setBackgroundImage:[UIImage imageForName:@"play"] forState:UIControlStateNormal];
    }
    return _playButton;
}

@end
